﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QSMonitor
{
    public partial class Form1 : Form
    {
        DataTable orderList = null;
        Dictionary<string, DataTable> detailDict = null;
        public Form1()
        {
            InitializeComponent();
            ucOrderList.RowEnter += new DataGridViewCellEventHandler(ucOrderList_RowEnter);
            progressBar1.Maximum = 5;
            progressBar1.Step = 1;
            /*
             * <strong>順利送達</strong>table8
             * http://www.t-cat.com.tw/Inquire/Trace.aspx?no=3171664250
             *Uri qs = new Uri("http://www.queenshop.com.tw/Login.asp");
             *webBrowser1.Url = qs;
             *http://www.queenshop.com.tw/OrderDetail.asp?od00=120302000253 
             */            
        }

        void ucOrderList_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = ucOrderList.GetDataGridViewCell(
                0,e.RowIndex);
            DataGridViewCell cellDate = ucOrderList.GetDataGridViewCell(
                3, e.RowIndex);
            DataTable dt = null;
            if (true.Equals(detailDict.TryGetValue(cell.Value.ToString()
                , out dt)))
            {
                if (cellDate.Value.ToString().Equals("無"))
                {
                    ucOrderDetail.SetData(dt);
                }
            }
            else
            {
                ucOrderDetail.NoData();
            }
        }

        void barStep()
        {
            progressBar1.PerformStep();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.PerformStep();
            ucBrowser1.NavigateURL("http://www.queenshop.com.tw/Login.asp");

            detailDict = new Dictionary<string, DataTable>();
            Dictionary<string, string> inputDict = new Dictionary<string, string>() 
            {
                {"userid",ucID.Text},
                {"password",ucPW.Text}
            };
            ucBrowser1.SetElementValueByName("input", "name", inputDict);
            progressBar1.PerformStep();
            //取得登入 button
            string[] images = { "登入" };
            List<HtmlElement> alBtn = ucBrowser1.GetElementByName(
                "input", "title", images);
            progressBar1.PerformStep();
            HtmlElement btn = alBtn[0] as HtmlElement;
            ucBrowser1.ElementInvok(btn, "click");
            progressBar1.PerformStep();
            //找出目前還沒出貨的訂單
            string[] orders = { "訂單編號", "最後處理日期", "訂單狀態", "出貨日期", "宅配狀態" };
            orderList = filterQSDataTable(
                ucBrowser1.GetDataByHtmlTable("orderlist"
                , createTable(orders), new int[] { 0, 1, 2, 3 }));
            ucOrderList.SetData(orderList);
            progressBar1.PerformStep();
        }
      
        /// <summary>
        /// 依所傳入的陣列建立DataTable
        /// </summary>
        /// <param name="p_cols"></param>
        /// <returns></returns>
        protected DataTable createTable(string[] p_cols)
        {
            DataTable dt = new DataTable();
            foreach (string colName in p_cols)
            {
                DataColumn col = new DataColumn();
                col.ColumnName = colName;
                col.DataType = typeof(System.String);
                dt.Columns.Add(col);
            }
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_dt"></param>
        /// <returns></returns>
        protected DataTable filterQSDataTable(DataTable p_dt)
        {
            IEnumerable<DataRow> query = 
                from x in p_dt.AsEnumerable()
                where x.Field<string>("出貨日期").Equals("無")
                select x;
            DataTable dt = query.CopyToDataTable<DataRow>();

            query = from x in p_dt.AsEnumerable()
                    where !x.Field<string>("出貨日期").Equals("無")
               select x;
            DataTable dt1 = query.CopyToDataTable<DataRow>();

            foreach (DataRow row in dt.Rows)
            {
                DataTable detail = getDetail(row[0].ToString());
                detailDict.Add(row[0].ToString(), detail);
            }

            string status = string.Empty;
            if (dt1.Rows.Count > 3)
            {
                for (int i = 0; i < 3; i++)
                {
                    DataRow row = dt.NewRow();
                     status = string.Empty;
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        row[col] = dt1.Rows[i][col].ToString();
                        if (col.Equals(0))
                        {
                            status = getGooodsStatus(dt1.Rows[i][col].ToString());
                        }
                    }
                    row["宅配狀態"] = status; 
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }
     
        DataTable getDetail(string p_orderNo)
        {
            string orderDetail = string.Format(
                "http://www.queenshop.com.tw/OrderDetail.asp?od00={0}"
                 , p_orderNo);
            ucBrowser1.NavigateURL(orderDetail);
            string[] details = { "物品名稱", "產品狀態" };
            int[] pos = { 2, 8 };

            DataTable dt = ucBrowser1.GetDataByHtmlTable("AutoNumber14"
                , createTable(details), pos);
           
            return dt;
        }

        /// <summary>
        /// 取得目前宅配狀態
        /// </summary>
        /// <param name="p_no"></param>
        /// <returns></returns>
        string getGooodsStatus(string p_orderNo)
        {
            string deliverStatus, goodsNo = getGoodsNO(p_orderNo);
            deliverStatus = string.Empty;
            if (goodsNo.Length.Equals(10))
            {
                string deliver = string.Format(
                    "http://www.t-cat.com.tw/Inquire/Trace.aspx?no={0}", goodsNo);
                ucBrowser1.NavigateURL(deliver);
                HtmlElement result = ucBrowser1.GetElementByID(
                    "ctl00_ContentBody_tblResult");
                HtmlElementCollection span = result.GetElementsByTagName("span");
                deliverStatus = span[3].InnerText;
            }
            return deliverStatus;
        }

        string getGoodsNO(string p_orderNo)
        {
            string orderDetail = string.Format(
                "http://www.queenshop.com.tw/OrderDetail.asp?od00={0}"
                 , p_orderNo);
            ucBrowser1.NavigateURL(orderDetail);
            List<HtmlElement> htmls = ucBrowser1.GetElementByName("div", "align"
                , new string[] { "center" });
            HtmlElement tbl = htmls[0] as HtmlElement;
            HtmlElementCollection tbls = null;
            tbls = tbl.GetElementsByTagName("table");
            tbls = tbls[1].GetElementsByTagName("table");
            HtmlElementCollection tds = tbls[0].GetElementsByTagName("td");
            return tds[tds.Count - 1].InnerText;
        }
    }
}
